//
// Created by yan on 6/14/17.
//

#include "yunbaapi/yunba_server.h"
#include <unistd.h>
yunba_server::yunba_server(string keystring )
{
    appkey = keystring ;
    conn_opts.keepAliveInterval = 300;
    conn_opts.reliable = 0;
    conn_opts.cleansession = 1;
    conn_opts.username = my_reg_info.username;
    conn_opts.password = my_reg_info.password;

}

int yunba_server::connect()
{
    int rc = 0;
    if (MQTTClient_connect(client, &conn_opts) != 0) {
        printf("connnect is failed!\n");
        return -1;
    }
    printf("connect is succes!\n");

    printf("init success\n");


    return 0;
}

int yunba_server::setup()
{
    int rc = 0;
    int res = MQTTClient_setup_with_appkey_and_deviceid_v2((char *)appkey.c_str(),deviceid ,&my_reg_info);
    if (res < 0) {
        printf("can't get info\n");
        return -1;
    }
    printf("get deviceid is ok!\n");
//----------------------------------------------------------------
    char url[200];
    res=MQTTClient_get_host_v2((char *)appkey.c_str(), url);
    if(res<0) {
        printf("can't get host info\n");
        return -1;
    }
    printf("Get url info: %s\n", url);
//---------------------------------------------------------------
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

    rc = MQTTClient_create(&client, url, my_reg_info.client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL);

//    rc = MQTTClient_setCallbacks(client, NULL, NULL, callbackmessage, NULL, callbackextened);
    printf("create success!\n");

    return 0;
//----------------------------------------------------------------
}

int yunba_server::pub(string data) {

    int rc = MQTTClient_publish(client, topic.c_str(), (int) data.size(), (void *) data.c_str());

    return rc;
}


